<template>
  <div class="carousel-container">
    <div class="carousel-content">
      <!-- 用户端轮播图展示 -->
      <div v-if="!isAdminLogin()" class="carousel-display">
        <el-carousel :interval="3000" type="card" height="500px" arrow="always">
          <el-carousel-item v-for="(item, index) in carouselImages" :key="index">
            <el-image
                :src="item.imageUrl"
                fit="cover"
                class="carousel-image"
                :preview-src-list="carouselImages.map(img => img.imageUrl)"
            />
          </el-carousel-item>
        </el-carousel>
      </div>

      <!-- 管理员端轮播图管理 -->
      <div v-else>
        <div class="admin-controls">
          <el-button type="primary" @click="handleAddImage">添加图片</el-button>
        </div>

        <el-row :gutter="20" class="image-list">
          <el-col
              v-for="(item, index) in carouselImages"
              :key="item.id"
              :span="6"
              class="image-item-col"
          >
            <div class="image-item">
              <el-image :src="item.imageUrl" fit="cover" class="thumbnail" />
              <div class="image-actions">
                <el-button
                    type="danger"
                    size="small"
                    @click="deleteImage(item.id, index)"
                >
                  删除
                </el-button>
              </div>
            </div>
          </el-col>
        </el-row>

        <!-- 添加图片对话框 -->
        <el-dialog v-model="addImageDialogVisible" title="添加轮播图" width="500px">
          <el-form label-width="80px">
            <el-form-item label="选择图片">
              <el-upload
                  class="avatar-uploader"
                  action="/api/upload/file"
                  :show-file-list="false"
                  :on-success="handleUploadSuccess"
                  :on-error="handleUploadError"
                  :before-upload="beforeUpload"
                  :on-progress="handleUploadProgress"
              >
                <img v-if="newImageUrl" :src="newImageUrl" class="uploaded-image-preview" />
                <div v-else-if="uploading" class="upload-progress">
                  <el-progress type="circle" :percentage="uploadProgress" :width="80" />
                </div>
                <el-icon v-else class="upload-icon"><Plus /></el-icon>
              </el-upload>

              <div v-if="newImageUrl" class="image-preview-url">
                <el-text size="small" type="info">图片已上传: {{ newImageUrl }}</el-text>
              </div>
              <div v-if="uploadError" class="upload-error">
                <el-text size="small" type="danger">{{ uploadError }}</el-text>
              </div>
            </el-form-item>
          </el-form>
          <template #footer>
            <div class="dialog-footer">
              <el-button @click="addImageDialogVisible = false">取消</el-button>
              <el-button
                  type="primary"
                  @click="addImage"
                  :disabled="!newImageUrl"
                  :loading="addingImage"
              >
                确定添加
              </el-button>
            </div>
          </template>
        </el-dialog>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import { Plus } from '@element-plus/icons-vue'
import carouselApi from '../api/carousel_api.js'

// 数据定义
const carouselImages = ref([])
const addImageDialogVisible = ref(false)
const newImageUrl = ref('')
const loginUser = ref({
  role: localStorage.getItem("role") || "user"
})
const addingImage = ref(false)
const uploading = ref(false)
const uploadProgress = ref(0)
const uploadError = ref('')

// 判断是否为管理员
const isAdminLogin = () => loginUser.value.role === 'admin'

// 获取轮播图数据
const fetchCarouselImages = async () => {
  try {
    const result = await carouselApi.list()
    carouselImages.value = (result || []).map(item => ({
      ...item,
      imageUrl: item.imageUrl || item.url // 保证字段统一
    }))
  } catch (error) {
    console.error('获取轮播图失败:', error)
    ElMessage.error('获取轮播图失败: ' + (error.message || '服务器错误'))
    carouselImages.value = [
      { id: 1, imageUrl: 'https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg' },
      { id: 2, imageUrl: 'https://fuss10.elemecdn.com/a/3f/3302e58f9a181d2509f3dc0fa68b0jpeg.jpeg' },
      { id: 3, imageUrl: 'https://fuss10.elemecdn.com/1/34/19aa98b1fcb2781c4fba33d850549jpeg.jpeg' },
      { id: 4, imageUrl: 'https://fuss10.elemecdn.com/0/6f/e35ff375812e6b0020b6b4e8f9571jpeg.jpeg' }
    ]
  }
}

// 上传前检查
const beforeUpload = (file) => {
  const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isJPG) {
    ElMessage.error('上传图片只能是 JPG/PNG 格式!')
    return false
  }
  if (!isLt2M) {
    ElMessage.error('上传图片大小不能超过 2MB!')
    return false
  }
  uploading.value = true
  uploadProgress.value = 0
  uploadError.value = ''
  newImageUrl.value = ''
  return true
}

// 上传进度
const handleUploadProgress = (event) => {
  if (event.percent) {
    uploadProgress.value = Math.round(event.percent)
  }
}

// 添加图片弹窗
const handleAddImage = () => {
  newImageUrl.value = ''
  uploadError.value = ''
  uploading.value = false
  uploadProgress.value = 0
  addImageDialogVisible.value = true
}

// 上传成功
const handleUploadSuccess = (response) => {
  uploading.value = false
  uploadProgress.value = 100
  if (response?.data) {
    newImageUrl.value = response.data
  } else if (response?.url) {
    newImageUrl.value = response.url
  } else {
    uploadError.value = '上传响应格式不正确'
    ElMessage.error('上传失败: 响应格式不正确')
    return
  }
  ElMessage.success('图片上传成功')
}

// 上传失败
const handleUploadError = (error) => {
  uploading.value = false
  uploadError.value = error.message || '上传失败'
  console.error('上传失败:', error)
  ElMessage.error('图片上传失败: ' + (error.message || '网络错误'))
}

// 确认添加
const addImage = async () => {
  if (!newImageUrl.value) {
    ElMessage.warning('请先上传图片')
    return
  }
  addingImage.value = true
  try {
    await carouselApi.add({ imageUrl: newImageUrl.value })
    ElMessage.success('轮播图添加成功')
    addImageDialogVisible.value = false
    newImageUrl.value = ''
    fetchCarouselImages()
  } catch (error) {
    console.error('添加轮播图失败:', error)
    if (error.code === 'ERR_BAD_RESPONSE' || (error.status && error.status >= 500)) {
      ElMessage.error('服务器内部错误，请联系管理员')
    } else {
      ElMessage.error('添加轮播图失败: ' + (error.message || '未知错误'))
    }
  } finally {
    addingImage.value = false
  }
}

// 删除图片
const deleteImage = async (id) => {
  try {
    await ElMessageBox.confirm('确认删除该图片吗？', '删除提示', {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    })
    await carouselApi.del(id)
    ElMessage.success('删除成功')
    fetchCarouselImages()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      if (error.code === 'ERR_BAD_RESPONSE' || (error.status && error.status >= 500)) {
        ElMessage.error('服务器内部错误，请联系管理员')
      } else {
        ElMessage.error('删除失败: ' + (error.message || '未知错误'))
      }
    }
  }
}

// 清理无效图片
const cleanupImages = async () => {
  try {
    await ElMessageBox.confirm('确认清理无效图片吗？此操作不可恢复！', '清理提示', {
      confirmButtonText: '确认清理',
      cancelButtonText: '取消',
      type: 'warning'
    })
    // 调用API清理无效图片
    ElMessage.success('清理成功')
    fetchCarouselImages()
  } catch (error) {
    if (error !== 'cancel') {
      console.log('用户取消清理')
    }
  }
}

onMounted(fetchCarouselImages)
</script>

<style scoped>
.carousel-container {
  padding: 40px 0;
  background-color: transparent;
  border-radius: 12px;
  box-shadow: 0 4px 18px rgba(0, 0, 0, 0.08);
}

.carousel-display {
  padding: 10px 0;
}

.carousel-image {
  width: 100%;
  height: 100%;
  border-radius: 12px;
  transition: transform 0.3s;
}

.carousel-image:hover {
  transform: scale(1.02);
}

.admin-controls {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
}

.image-list {
  margin-top: 10px;
}

.image-item-col {
  margin-bottom: 20px;
}

.image-item {
  border: 1px solid #ebeef5;
  border-radius: 8px;
  overflow: hidden;
  position: relative;
  transition: box-shadow 0.3s;
}

.image-item:hover {
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.15);
}

.thumbnail {
  width: 100%;
  height: 200px;
  display: block;
  object-fit: cover;
}

.image-actions {
  position: absolute;
  bottom: 8px;
  right: 8px;
  opacity: 0;
  transition: opacity 0.3s;
}

.image-item:hover .image-actions {
  opacity: 1;
}

.avatar-uploader {
  width: 100%;
  height: 300px;
  border: 1px dashed #d9d9d9;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}

.avatar-uploader:hover {
  border-color: #409eff;
}

.upload-icon {
  font-size: 32px;
  color: #8c939d;
}

.uploaded-image-preview {
  width: 100%;
  height: 300px;
  object-fit: contain;
}

.upload-progress {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.image-preview-url {
  margin-top: 10px;
  word-break: break-all;
}

.upload-error {
  margin-top: 10px;
  color: #f56c6c;
}
</style>
